package com.youthfilmic.yuejian.weixin.pay;

import com.alibaba.druid.util.StringUtils;
import com.youthfilmic.yuejian.dao.ApplicationDao;
import com.youthfilmic.yuejian.dao.TextInfoDao;
import com.youthfilmic.yuejian.dao.UserDao;
import com.youthfilmic.yuejian.domain.Application;
import com.youthfilmic.yuejian.domain.TextInfo;
import com.youthfilmic.yuejian.domain.User;
import com.youthfilmic.yuejian.util.StringUtil;
import com.youthfilmic.yuejian.util.XMLUtil;
import com.youthfilmic.yuejian.weixin.core.ResultConfig;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * Created by youweixi on 15/10/7.
 */
@Controller
@RequestMapping("/weixin/pay")
public class WeixinPayController {
    @Resource
    private UserDao userDao;
    @Resource
    private ApplicationDao applicationDao;



    /**
     * @title make微信订单接口
     * */
    @RequestMapping(value = "/getNewOrderInfo" , method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getNewOrderInfo(
            HttpSession session,
            @RequestParam(value="applicationId",required = false) Long applicationId
    ){
        Long id = (Long)session.getAttribute("userId");
        User user = null;
        if (id != null) user = userDao.findOne(id);
        if (user == null){
            return ResultConfig.getResult(ResultConfig.STATUS_GLOBAL_USER_NOT_LOGIN , "not login or the user is not a weixin user");
        }
        if (applicationId == null){
            return ResultConfig.getResult(ResultConfig.STATUS_GLOBAL_PARAM_IS_WRONG , "param is wrong");
        }
        Application application = applicationDao.findOne(applicationId);
        if (application == null){
            return ResultConfig.getResult(ResultConfig.STATUS_GLOBAL_PARAM_IS_WRONG , "param is wrong");
        }
        //不是等待支付状态（说明已经支付了）
        if(application.getStatus() != Application.STATUS_WAIT_FOR_PAID){
            return ResultConfig.getResult(ResultConfig.STATUS_PAY_ALREADY_PAID , "already paid");
        }else{
            //创建订单
            String orderId = String.valueOf(application.getId());
            if (application.getId() < 10){
                orderId = '0' + String.valueOf(application.getId());
            }

            UnifiedOrder order = new UnifiedOrder(user.getOpenId() , application.getPrice() , application.getSubjectTitle() , orderId);
            return order.getJsonResult();
        }
    }

}
